import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { useAuthStore } from "../store/auth";
import { useSystemStore } from "../store/system";

export const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
});

request.interceptors.response.use(
  (response) => {
    const config = response.config as _AxiosRequestConfig;

    if (response.data.code === 401) {
      useAuthStore.getState().logout();
    }

    if (!config.noErrMessage && response.data.code !== 200) {
      useSystemStore.getState().message("error", response.data?.msg);
    }

    return response.data;
  },
  (err) => {
    useSystemStore.getState().message("error", "网络错误");
    return { code: 400, msg: err.message } as ResBody;
  }
);

request.interceptors.request.use((config) => {
  const _config = config as _AxiosRequestConfig;
  if (!_config.headers.get("Content-Type")) {
    //默认携带这个头
    _config.headers.set("Content-Type", "application/json");
  }
  if (!_config.headers.get("Authorization")) {
    const token = localStorage.getItem("token");
    _config.headers.set("Authorization", token);
  }
  return _config;
});

export interface ResBody {
  code: number;
  msg?: string;
  total?: number;
  [key: string]: any;
}

export interface _AxiosRequestConfig extends InternalAxiosRequestConfig {
  noErrMessage: boolean; //不全局处理错误信息
  noToken: boolean; //不发送token
}
